<template>
  <div id="editor"></div>
</template>

<script>
import E from "wangeditor";

export default {
  data () {
    return {
      config: {},
      files: [],
      editor: null,
      content: "",
      xss: null,
    };
  },
  methods: {
    async handleUpload (file) {
      // 上传风采
      const params = new FormData();
      params.append("files", file[0]);
      const res = await this.$http.uploadFile(params);
      if (res.code !== 200) return this.$message.error(res.message);
      this.files.push(res.files[0]);
      return res.files[0];
    },
    async insertImg (resultFiles, insertImgFn) {
      // resultFiles 是 input 中选中的文件列表
      // handleUpload(resultFiles)
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      // 上传图片，返回结果，将图片插入到编辑器中
      const img = await this.handleUpload(resultFiles);
      insertImgFn(img);
    },
    // 让最终的子组件发起申请 减少跨过多组件的信息传输
    async toSubmit (form) {
      // 将内容转为 和html
      this.content = this.editor.txt.html();
      // 将html 转为安全html 避免xss攻击
      form.activitycontentDisc = this.xss(this.content);

      // 异步发起请求
      const params = {
        activityId: form.activityId,
        activitycontentDatetime: form.activitycontentDatetime,
        activitycontentDisc: form.activitycontentDisc,
        activitycontentTitle: form.activitycontentTitle,
      };
       await this.$http.activityContentPost(params);
    },

  },
  components: {},
  mounted () {
    const editor = new E("#editor");
    const xss = require("xss");
    // 预置编辑器的内容
    editor.config.placeholder = "请输入正文";
    editor.config.focus = false;
    editor.config.showFullScreen = true;
    editor.config.customUploadImg = (e, v) => this.insertImg(e, v);
    editor.create();
    this.editor = editor;
    this.xss = xss;
  },
};
</script>

<style scoped>
</style>
